<?php


namespace App\Models\CacheModel\zlcr2;


use app\common\lib\exception\ApiException;
use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

class Zlcr2UserAddQuestion extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr2_user_add_question';

    protected $cacheModel = 'question_answer.add_question';

    /**
     * 新增问答信息
     */
    public function SaveData($qid, $data)
    {
        try {
            $id = $this->insertGetId($data);
            // 添加至我的问答-提问列表
            if ($data['status'] === 2) {   // 添加至追问列表
                $this->listDataAdd($qid, [$id => $data['pay_time']]);
            }
            return $id;
        } catch (\Exception $e) {
            Log::write('问答 Zlcr2UserAddQuestion model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return 0;
        }
    }

    /**
     * 更新问答信息
     */
    public function UpdateData($qid, $id, $data)
    {
        try {
            $this->where(['id' => $id])->update($data);

            if (isset($data['status']) && $data['status'] === 2) {   // 添加至追问列表
                $this->listDataAdd($qid, [$id => $data['pay_time']]);
            }
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data);

            return true;
        } catch (\Exception $e) {
            Log::write('问答 Zlcr2UserAddQuestion model => UpdateData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 获取问题追问   信息
     */
    public function getQuestionAddQuestionInfo($qid)
    {
        request()->get(['page' => -1]);
        $pageData = $this->getListPage($qid, 'id', [], 0, 'asc');

        $resData = [];
        foreach ($pageData['data'] as $datum) {
            if (in_array((int)$datum['status'], [2, 4, 5, 6, 7, 8], true)) {
                $resData[] = [
                    'id' => (int)$datum['id'],
                    'qid' => $datum['qid'],
                    'answer_duration' => (int)$datum['answer_duration'],
                    'order_num' => $datum['order_num'],
                    'reply_time' => (int)$datum['reply_time'],
                    'create_time' => (int)$datum['create_time'],
                    'status' => (int)$datum['status'],
                    'pay_time' => (int)$datum['pay_time'],
                    'question' => $datum['question'],
                    'activity_discount' => $datum['activity_discount'],
                    'answer_content' => $datum['answer_content'],
                    'reply_type' => (int)$datum['reply_type'],
                    'reply_uid' => (int)$datum['reply_uid'],
                    'cannel_cause' => $datum['cannel_cause'],
                    'cannel_tag_name' => $datum['cannel_tag_name'],
                    'supplement_answer' => $datum['supplement_answer'] ? json_decode($datum['supplement_answer'], true) : []
                ];
            }
        }

        return $resData;
    }

    /**
     * 获取当前问题追问次数
     * @param $qid
     * @param int $filterInvalid 是否过滤无效提问【占星师申述取消，追问回复超时已取消，用户申述通过退款】 1=>过滤 0=>不过滤
     * @return int
     * @throws \Exception
     */
    public function getQuestionAddQuestionNum($qid, $filterInvalid = 0): int
    {
        request()->get(['page'=>-1]);
        $pageData = $this->getListPage($qid, 'id', [], 0, 'asc');
        $statusList = $filterInvalid === 1 ? [2, 4] : [2, 4, 5, 6, 7, 8];
        $num = 0;
        foreach ($pageData['data'] as $datum) {
            if (in_array($datum['status'], $statusList, false)) {
                $num++;
            }
        }

        return $num;
    }

    /**
     * 获取问题是否追问过
     * @param $qid
     * @return bool
     * @throws \Exception
     */
    public function getQuestionIsAddQuestion($qid): bool
    {
        $pageData = $this->getQuestionAddQuestionNum($qid, 0);

        return $pageData['data'] ? true : false;
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     * @throws ApiException
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try {
            if ($ids) {
                $where = ['id' => ['in', $ids]];
            } else {
                $where = ['qid' => $type[0], 'status' => ['in', [2, 4, 5, 6, 7, 8]]];
            }
            $data = $this
                ->where($where)
                ->order('pay_time ', $sortType)
                ->column('qid,status,activity_discount,order_num,question,create_time,answer_content,answer_duration,reply_time,pay_time,reply_type,reply_uid,cannel_tag_name,cannel_cause,supplement_answer', 'id');
            foreach ($data as $datum)
            {
                if (isset($datum['status']) && $datum['status'] == 1)
                {   // 缓存时间
                    CacheManage::getInstance()->setCacheTime(1);
                }
            }
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 获取当前问答问题待解答的追问数据
     * @param $qid
     * @return array
     */
    public function getAddQuestionByNotAnswer($qid)
    {
        try {
            return $this->where(['qid' => $qid, 'status' => 2])->order('id desc')->findOrFail()->toArray();
        } catch (\Exception $e) {
            Log::write('问答 Zlcr2UserAddQuestion model => getAddQuestionByNotAnswer() 获取未解答的追问数据异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return [];
        }
    }

    /**
     * 获取当前问答问题最后一条的已完成追问数据
     * @param $qid
     * @return array
     */
    public function getAddQuestionByLastSuccess($qid)
    {
        try {
            return $this->where(['qid' => $qid, 'status' => 4])->order('id desc')->findOrFail()->toArray();
        } catch (\Exception $e) {
            Log::write('问答 Zlcr2UserAddQuestion model => getAddQuestionByLastSuccess() 获取当前问答问题最后一条的已完成追问数据：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return [];
        }
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        foreach ($resData as $orderId => $questionItemData) {
            $resData[$orderId] = arrayKeyData2int($questionItemData, ['create_time', 'status', 'answer_duration', 'reply_time', 'id', 'pay_time', 'reply_uid', 'reply_type']);

            if (isset($questionItemData['supplement_answer'])) {
                $resData[$orderId]['supplement_answer'] = $questionItemData['supplement_answer'] ? json_decode($questionItemData['supplement_answer'], true) : [];
            }
        }

        return $resData;
    }
}
